// pages/game/game.js
// 示例词库
const words = [
  '苹果', '香蕉', '橙子', '西瓜', '葡萄',
  '电脑', '手机', '电视', '冰箱', '空调',
  '足球', '篮球', '排球', '网球', '乒乓球',
  '医生', '老师', '警察', '司机', '厨师',
  '北京', '上海', '广州', '深圳', '杭州'
];

const GRID_SIZE = 20; // 网格大小
const GAME_SPEED = 200; // 游戏速度（毫秒）

Page({

  /**
   * 页面的初始数据
   */
  data: {
    timeLeft: 180, // 3分钟
    score: 0,
    currentWord: '',
    isGameOver: false,
    words: [],
    correctWords: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    console.log('游戏页面加载');
    this.initGame();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    console.log('游戏页面准备完成');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log('游戏页面显示');
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('游戏页面卸载');
    this.stopGame();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  initGame() {
    console.log('初始化游戏');
    // 获取游戏设置
    const gameTime = wx.getStorageSync('gameTime') || 3;
    const timeInSeconds = gameTime * 60;

    // 随机打乱词库顺序
    const shuffledWords = [...words].sort(() => Math.random() - 0.5);
    this.setData({
      timeLeft: timeInSeconds,
      score: 0,
      words: shuffledWords,
      currentWord: shuffledWords[0],
      isGameOver: false,
      correctWords: 0
    }, () => {
      console.log('游戏数据初始化完成', this.data);
      this.startTimer();
    });

    // 获取画布上下文
    const query = wx.createSelectorQuery();
    query.select('#gameCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        console.log('获取画布信息：', res);
        if (!res[0]) {
          console.error('未找到画布元素');
          return;
        }

        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        // 设置画布大小
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.scale(dpr, dpr);

        this.canvas = canvas;
        this.ctx = ctx;
        this.canvasWidth = res[0].width;
        this.canvasHeight = res[0].height;
        this.gridWidth = this.canvasWidth / GRID_SIZE;
        this.gridHeight = this.canvasHeight / GRID_SIZE;

        console.log('画布初始化完成', {
          width: this.canvasWidth,
          height: this.canvasHeight,
          gridWidth: this.gridWidth,
          gridHeight: this.gridHeight
        });

        // 初始化游戏状态
        this.resetGame();
        this.startGame();
      });
  },

  startTimer() {
    console.log('开始计时器');
    this.timer = setInterval(() => {
      if (this.data.timeLeft <= 0) {
        this.endGame();
        return;
      }
      this.setData({
        timeLeft: this.data.timeLeft - 1
      });
    }, 1000);
  },

  handleCorrect() {
    const newScore = this.data.score + 10;
    this.setData({ 
      score: newScore,
      correctWords: this.data.correctWords + 1
    });
    this.nextWord();
  },

  handleSkip() {
    this.nextWord();
  },

  nextWord() {
    const currentIndex = this.data.words.indexOf(this.data.currentWord);
    if (currentIndex < this.data.words.length - 1) {
      this.setData({
        currentWord: this.data.words[currentIndex + 1]
      });
    } else {
      this.endGame();
    }
  },

  endGame() {
    console.log('游戏结束');
    clearInterval(this.timer);
    this.setData({ isGameOver: true });
    
    // 更新最高分
    const bestScore = wx.getStorageSync('bestScore') || 0;
    if (this.data.score > bestScore) {
      wx.setStorageSync('bestScore', this.data.score);
    }
    
    // 更新总场次
    const totalGames = wx.getStorageSync('totalGames') || 0;
    wx.setStorageSync('totalGames', totalGames + 1);

    // 更新历史记录
    const historyList = wx.getStorageSync('historyList') || [];
    const now = new Date();
    const historyItem = {
      score: this.data.score,
      date: `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`,
      time: 180 - this.data.timeLeft,
      correctWords: this.data.correctWords
    };
    historyList.unshift(historyItem);
    wx.setStorageSync('historyList', historyList);

    // 更新排行榜
    const rankList = wx.getStorageSync('rankList') || [];
    rankList.push(historyItem);
    rankList.sort((a, b) => b.score - a.score);
    // 只保留前50名
    wx.setStorageSync('rankList', rankList.slice(0, 50));
  },

  restartGame() {
    console.log('重新开始游戏');
    this.resetGame();
    this.startGame();
  },

  goToHome() {
    console.log('返回首页');
    wx.navigateBack();
  },

  resetGame() {
    console.log('重置游戏状态');
    // 初始化蛇的位置和方向
    this.snake = [
      { x: 10, y: 10 },
      { x: 9, y: 10 },
      { x: 8, y: 10 }
    ];
    this.direction = 'right';
    this.nextDirection = 'right';
    this.food = this.generateFood();
    this.score = 0;
    this.isGameOver = false;
    this.setData({ score: 0, isGameOver: false });
  },

  startGame() {
    console.log('开始游戏循环');
    this.gameLoop = setInterval(() => {
      this.update();
      this.draw();
    }, GAME_SPEED);
  },

  stopGame() {
    console.log('停止游戏循环');
    if (this.gameLoop) {
      clearInterval(this.gameLoop);
      this.gameLoop = null;
    }
  },

  update() {
    // 更新蛇的方向
    this.direction = this.nextDirection;

    // 获取蛇头位置
    const head = { ...this.snake[0] };

    // 根据方向移动蛇头
    switch (this.direction) {
      case 'up':
        head.y--;
        break;
      case 'down':
        head.y++;
        break;
      case 'left':
        head.x--;
        break;
      case 'right':
        head.x++;
        break;
    }

    // 检查是否撞墙
    if (head.x < 0 || head.x >= this.gridWidth || head.y < 0 || head.y >= this.gridHeight) {
      this.gameOver();
      return;
    }

    // 检查是否撞到自己
    for (let i = 0; i < this.snake.length; i++) {
      if (head.x === this.snake[i].x && head.y === this.snake[i].y) {
        this.gameOver();
        return;
      }
    }

    // 移动蛇
    this.snake.unshift(head);

    // 检查是否吃到食物
    if (head.x === this.food.x && head.y === this.food.y) {
      this.score += 10;
      this.setData({ score: this.score });
      this.food = this.generateFood();
    } else {
      this.snake.pop();
    }
  },

  draw() {
    if (!this.ctx) {
      console.error('画布上下文不存在');
      return;
    }

    const ctx = this.ctx;
    const gridSize = GRID_SIZE;

    // 清空画布
    ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);

    // 绘制蛇
    ctx.fillStyle = '#4CAF50';
    this.snake.forEach((segment, index) => {
      if (index === 0) {
        // 蛇头用深色
        ctx.fillStyle = '#388E3C';
      } else {
        ctx.fillStyle = '#4CAF50';
      }
      ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize - 1, gridSize - 1);
    });

    // 绘制食物
    ctx.fillStyle = '#FF5722';
    ctx.fillRect(this.food.x * gridSize, this.food.y * gridSize, gridSize - 1, gridSize - 1);
  },

  generateFood() {
    let food;
    do {
      food = {
        x: Math.floor(Math.random() * this.gridWidth),
        y: Math.floor(Math.random() * this.gridHeight)
      };
    } while (this.snake.some(segment => segment.x === food.x && segment.y === food.y));
    return food;
  },

  gameOver() {
    console.log('游戏结束');
    this.stopGame();
    this.isGameOver = true;
    this.setData({ isGameOver: true });

    // 更新最高分
    const highScore = wx.getStorageSync('highScore') || 0;
    if (this.score > highScore) {
      wx.setStorageSync('highScore', this.score);
    }
  },

  handleUp() {
    if (this.direction !== 'down') {
      this.nextDirection = 'up';
    }
  },

  handleDown() {
    if (this.direction !== 'up') {
      this.nextDirection = 'down';
    }
  },

  handleLeft() {
    if (this.direction !== 'right') {
      this.nextDirection = 'left';
    }
  },

  handleRight() {
    if (this.direction !== 'left') {
      this.nextDirection = 'right';
    }
  }
})